<script setup lang="ts">
import { ref, onMounted, watch, toRaw, computed } from "vue";
import { getDeviceConfigApi, setDeviceConfigApi } from '@/api/configs/deviceConfig';
import { useI18n } from "vue-i18n";
import { DeviceModel } from "@/api/products/device";
import { formatTimestampToDatetime } from "@/utils/appCommon/timeUtil";
import { ElMessageBox, ElMessage } from "element-plus";

const emit = defineEmits(['onsubmit']);

const props = defineProps({
  params: {
    type: Object,
    required: true
  },
  deviceNo: {
    type: String,
    required: true
  },
  deviceOptions: {
    type: Array,
    required: false,
    default: [],
  },
  forceRefresh: {
    type: Number,
    required: false,
    default: 0
  }
});

// TypeScript接口定义，对应后端结构体
interface AeFrpItem {
  enable: boolean;
  serverIp: string;
  serverPort: number;
  remotePort: number;
  tcpMux: boolean;
  tcpMuxConnectTimeout: number;
  heartbeatInterval: number;
  heartbeatTimeout: number;
  updatetime?: number;
}

const i18n = useI18n();

const current = ref({
  configKey: "frp", // 固定configKey为frp
  deviceNo: "",
  productId: 0,
  productKey: "",
  updatedAt: 0,
});

const currentDeviceInfo = ref<DeviceModel>();

const defaultForm = {
  enable: false,
  serverIp: "",
  serverPort: 7000,
  remotePort: 8000,
  tcpMux: true,
  tcpMuxConnectTimeout: 10,
  heartbeatInterval: 30,
  heartbeatTimeout: 90
}

// 表单数据初始化
const form = ref<AeFrpItem>(Object.assign({}, defaultForm));

// 监听属性变化，加载配置
watch(
  () => props,
  (newVal) => {
    current.value.updatedAt=0
    current.value.deviceNo = newVal.deviceNo;
    current.value.productId = newVal.params.productId;
    current.value.productKey = newVal.params.productKey;
    setTimeout(async () => {
      await loadConfig();
    });
  },
  {
    deep: true, immediate: true
  }
);

// 格式化系统时间
const systemTime = computed(() => {
  if (!current.value.updatedAt || current.value.updatedAt == 0) {
    return "-";
  }
  return formatTimestampToDatetime(current.value.updatedAt);
});

const loading = ref(false);

// 加载配置
const loadConfig = async () => {
  try {
    loading.value = true;
    const res = await getDeviceConfigApi({
      deviceNo: current.value.deviceNo,
      configKey: current.value.configKey,
    });
    if (res.data?.configValue) {
      form.value = JSON.parse(res.data?.configValue);
      form.value.updatetime =  res.data?.updatedAt
      // 更新当前时间戳
      if (form.value.updatetime) {
        current.value.updatedAt = form.value.updatetime;
      }
    }
  } finally {
    loading.value = false;
  }
};

// 验证端口范围
const validatePort = (port: number): boolean => {
  return port >= 1 && port <= 65535;
};

// 验证配置
const validateConfig = (): boolean => {
  // 如果启用了FRP，则需要验证必填字段
  if (form.value.enable) {
    if (!form.value.serverIp.trim()) {
      ElMessage.error(i18n.t('device.frp.SERVER_IP_REQUIRED'));
      return false;
    }

    if (!validatePort(form.value.serverPort)) {
      ElMessage.error(i18n.t('device.frp.INVALID_SERVER_PORT'));
      return false;
    }

    if (!validatePort(form.value.remotePort)) {
      ElMessage.error(i18n.t('device.frp.INVALID_REMOTE_PORT'));
      return false;
    }
  }

  return true;
};

// 保存配置
const saveConfig = async () => {
  try {
    loading.value = true;

    // 验证配置
    if (!validateConfig()) {
      return;
    }

    // 准备请求数据
    const reqData = { ...toRaw(form.value) };

    await setDeviceConfigApi({
      deviceNo: current.value.deviceNo,
      configKey: current.value.configKey,
      configValue: reqData
    });

    ElMessage.success(i18n.t('buttons.tips.success'));

    // 重新加载配置以更新时间戳
    setTimeout(async ()=>{
      await loadConfig();
    },2000)

  } catch (error) {
    ElMessage.error(error.message || i18n.t('buttons.tips.fail'));
  } finally {
    loading.value = false;
  }
};

// 带二次确认的保存方法
const handleSaveConfig = async () => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      i18n.t('buttons.tips.confirmSaveConfig') + "?",
      "",
      {
        confirmButtonText: i18n.t('buttons.confirm'),
        cancelButtonText: i18n.t('buttons.cancel'),
        type: 'warning'
      }
    );

    // 用户确认后执行保存操作
    await saveConfig();
  } catch (error) {
    // 用户取消或其他错误，不做任何操作
    console.log('保存已取消');
  }
};

// 填入默认值方法
const fillDefaultValues = () => {
  form.value = Object.assign({}, defaultForm);
  ElMessage.success(i18n.t('device.frp.FILL_DEFAULT_SUCCESS'));
};

onMounted(() => {
});
</script>

<template>
  <div class="ae-frp-config">
    <el-form :model="form" class="vertical-form">
      <!-- 设备编号 -->
      <el-form-item :label="i18n.t('device.deviceNo')" prop="deviceNo">
        <el-input v-model="current.deviceNo" disabled style="width: 100%; max-width: 300px;" />
      </el-form-item>

      <!-- FRP 启用 -->
      <el-form-item :label="'enable'" prop="enable">
        <div style="margin-top: 8px;">
          <el-radio-group v-model="form.enable">
            <el-radio :label="true" style="margin-right: 20px;">{{ i18n.t('buttons.yes') }}</el-radio>
            <el-radio :label="false">{{ i18n.t('buttons.no') }}</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>

      <!-- 服务器IP -->
      <el-form-item :label="'server_ip'" prop="serverIp">
        <el-input v-model="form.serverIp" placeholder="server-IP" style="width: 100%; max-width: 300px;" />
      </el-form-item>

      <!-- 服务器端口 -->
      <el-form-item :label="'server_port'" prop="serverPort">
        <el-input-number v-model="form.serverPort" :min="1" :max="65535" :step="1" style="width: 100%; max-width: 200px;" />
      </el-form-item>

      <!-- 远程端口 -->
      <el-form-item :label="'remote_port'" prop="remotePort">
        <el-input-number v-model="form.remotePort" :min="1" :max="65535" :step="1" style="width: 100%; max-width: 200px;" />
      </el-form-item>

      <!-- TCP多路复用 -->
      <el-form-item :label="'tcp_mux'" prop="tcpMux">
        <div style="margin-top: 8px;">
          <el-radio-group v-model="form.tcpMux">
            <el-radio :label="true" style="margin-right: 20px;">{{ i18n.t('buttons.yes') }}</el-radio>
            <el-radio :label="false">{{ i18n.t('buttons.no') }}</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>

      <!-- TCP多路复用连接超时 -->
      <el-form-item :label="'tcp_mux_connect_timeout'" prop="tcpMuxConnectTimeout">
        <el-input-number v-model="form.tcpMuxConnectTimeout" :min="1" :step="1" style="width: 100%; max-width: 200px;" />
      </el-form-item>

      <!-- 心跳间隔 -->
      <el-form-item :label="'heartbeat_interval'" prop="heartbeatInterval">
        <el-input-number v-model="form.heartbeatInterval" :min="1" :step="1" style="width: 100%; max-width: 200px;" />
      </el-form-item>

      <!-- 心跳超时 -->
      <el-form-item :label="'heartbeat_timeout'" prop="heartbeatTimeout">
        <el-input-number v-model="form.heartbeatTimeout" :min="1" :step="1" style="width: 100%; max-width: 200px;" />
      </el-form-item>

      <!-- 系统时间 -->
      <el-form-item :label="'system_time'">
        <el-input v-model="systemTime" type="text" disabled style="width: 100%; max-width: 300px;" />
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="handleSaveConfig" style="min-width: 150px; margin-right: 10px;">
          {{ i18n.t('buttons.submit') }}
        </el-button>
        <el-button @click="fillDefaultValues" style="min-width: 150px;">
          {{ i18n.t('device.frp.FILL_DEFAULT') }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.ae-frp-config {
  padding: 20px;
  overflow-x: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

@media (max-width: 768px) {
  .vertical-form {
    max-width: 100%;
  }

  .el-form-item__label {
    width: 120px !important;
  }
}
</style>
